<?php
/*
 * @Author: your name
 * @Date: 2020-12-23 12:01:16
 * @LastEditTime: 2020-12-28 10:33:41
 * @LastEditors: Please set LastEditors
 * @Description: 官方规则
 * @FilePath: /special/application/adminapiv3/service/module_manage/hgshield/NormalRuleGroup.php
 */

namespace app\adminapiv3\service;


use app\common\service\HostNormalRuleGroupRelation;
use app\common\service\HostNormalRuleRelation;

class NormalRuleGroup extends BaseService
{
    /**
     * @name 列表
     * @param $host_id
     * @param $params
     * @return array
     * @author wx
     * @date 2019/11/12 13:24
     */
    public function list($host_id, $params)
    {
        //1. 更改 官方规则组的总数和使用
        $this->modifyNumUsed($host_id);

        //2. 查询数据
        $server = new \app\common\service\NormalRuleGroup();
        $list = $server->list($host_id, $params);

        return $list;
    }

    /**
     * @name 修改
     * @param $host_id
     * @param $id
     * @param $updateData
     * @return bool
     * @author wx
     * @date 2019/12/24 11:10
     */
    public function modify($host_id, $id, $updateData)
    {
        //1. 修改host_normal_group_relation
        $server = new HostNormalRuleGroupRelation();
        $server->modify(['host_id' => $host_id, 'group_id' => $id], $updateData);

        //2. 修改host_normal_rule_raletion
        $ruleServer = new HostNormalRuleRelation();
        $ruleServer->modify(['host_id' => $host_id, 'group_id' => $id], $updateData);

        $this->modifyNumUsed($host_id);

        return true;
    }



    /**
     * @name 修改总数
     * @param $host_id
     * @author wx
     * @date 2019/12/24 10:56
     */
    public function modifyNumUsed($host_id)
    {
        $ruleRelationServer = new HostNormalRuleRelation();
        $total = $ruleRelationServer->total($host_id);

        $used = $ruleRelationServer->used($host_id);

        $groupRelationServer = new HostNormalRuleGroupRelation();

        foreach ($total as $k => $v){
            $num = isset($used[$k]) ? $used[$k] : 0;
            $updateData['total'] = $v;
            $updateData['used'] = $num;
            $updateData['status'] = $num == 0 ? 0 : 1;

            $groupRelationServer->modify(['host_id' => $host_id, 'group_id' => $k], $updateData);
        }
    }
}